import React, { useEffect, useMemo, useState } from 'react';

import SyncScreen from '../SyncScreen';
import VideoItem from './VideoItem';
import { useScreenSync } from '../Context/ScreenSyncContext';
import { useBusiness } from '../Context/BusinessContext';
import { IStream, useStream } from '../Context/StreamContext';
import AgentService from '@/modules/Agent';
import { useTranslation } from 'react-i18next';
import { ILayout, IOperationName } from '@/modules/interface';
import { resizeWin } from '@/utils/resize';
import AuthorizationTips from './AuthorizationTips';
import styled from '@emotion/styled';
import InviteInstruction from './InviteInstruction';
import useSyncState from '../hooks/useSyncState';

interface OtherStreamProps {
	layout?: string;
	width?: string;
	height?: string;
	hangup?: () => void;
}

interface agentStream {
	id: string;
	label: string;
	audioOnly: boolean;
	clientId: string;
	muteStatus: boolean;
	streamMode: string;
	role: string;
	isScreenSyncMode: boolean;
	userName: string;
}

const InviteBox = styled.div`
	width: 100%;
	height: 100%;
	background: url(${require('../../assets/img/invite-background-img.png')}) no-repeat;
	background-size: 100% 100%;
	position: absolute;
	top: 0;
`;

const defaultMediaData: IStream[] = [
	{ id: '', label: '', audioOnly: false, clientId: '', muteStatus: false, videoId: '', streamMode: 'video', role: '', userName: '', isScreenSyncMode: false },
	{ id: '', label: '', audioOnly: false, clientId: '', muteStatus: false, videoId: '', streamMode: 'video', role: '', userName: '', isScreenSyncMode: false },
	{ id: '', label: '', audioOnly: false, clientId: '', muteStatus: false, videoId: '', streamMode: 'video', role: '', userName: '', isScreenSyncMode: false }
];

const OtherStream = (props: OtherStreamProps) => {
	const { t } = useTranslation();
	const { layout, width, height, hangup } = props;
	const { smallStream, audioStreams } = useStream();
	const [currentStreams, setCurrentStreams] = useState<IStream[]>(defaultMediaData);
	const [renderedLabel, setRenderedLabel] = useSyncState<string[]>([]);

	useEffect(() => {
		if (!AgentService.sessionId) {
			setCurrentStreams(defaultMediaData);
		}
		return () => {
			setCurrentStreams(defaultMediaData);
		};
	}, []);

	useEffect(() => {
		let list = [...defaultMediaData];
		let idx = 0;
		smallStream().map((stream, index) => {
			list[index] = stream;
		});

        console.log('log-smallStream:', smallStream(), new Date().toISOString());

		setCurrentStreams(list.sort((a: IStream, b: IStream) => (a.userName === AgentService.user?.userName ? -1 : 0)));
		// setCurrentStreams(list);

		setSpeaker();
	}, [smallStream()]);

	const { screenSyncState, zcoScreenSync } = useScreenSync();

	const calculatorLiClassNames = (layout: ILayout): string => {
		return resizeWin(AgentService.rootContainer).Width > 1199 ? `pc-${layout}-li` : `pad-${layout}-li`;
	};

	const calculatorVideoClassNames = (layout: ILayout): string => {
		return resizeWin(AgentService.rootContainer).Width > 1199 ? `pc-${layout}-video-box` : `pad-${layout}-video-box`;
	};

	const setSpeaker = () => {
		smallStream().map(async item => {
			const defaultSperakerID = AgentService.getSpeakerDeviceID() ? AgentService.getSpeakerDeviceID() : AgentService.getDefaultSpeaker();

			if (defaultSperakerID && item.id) {
				await AgentService.switchSpeaker(item.id, defaultSperakerID);
			}
		});
	};

	const renderItem = (item: any) => {
        console.log('log-renderItem:', item, new Date().toISOString());

		if (item) {
			console.log('renderItem:', item, AgentService.getSessionClientWithClientID(item.label));
		}

		if (!item.label || AgentService.getSessionClientWithClientID(item.label)?.status === 'idle') {
			return (
				<>
					<span className="video-desc" style={{ fontSize: '14px' }}>
						{t('no-calls')}
					</span>
				</>
			);
		}

		if (item.id?.indexOf(IOperationName.INVITE) !== -1) {
			return (
				<>
					<InviteBox>
						<InviteInstruction />
					</InviteBox>
				</>
			);
		}

		if (AgentService.getSessionClientWithLabel(item.label)?.status === 'permission' || AgentService.getSessionClientWithLabel(item.label)?.status === 'publish') {
			return <AuthorizationTips size={16} status={AgentService.getSessionClientWithLabel(item.label)?.status || 'idle'} />;
		}

		if (AgentService.getSessionClientWithLabel(item.label)?.status === 'published' && renderedLabel().indexOf(item.label) === -1) {
			return (
				<>
					<VideoItem {...item} customerRole={AgentService.getSessionClientWithLabel(item.label)?.customerRole || ''} hangup={hangup} />
				</>
			);
		}
	};

	const renderView = useMemo(() => {
		return currentStreams.map((item, index) => {
            console.log('log-currentStreams', currentStreams, new Date().toISOString());
			return (
				// 设置唯一key，避免排序时，导致组件重新渲染
				<li className={calculatorLiClassNames(layout as ILayout)} key={`${item.id}` || index}>
					<div className={calculatorVideoClassNames(layout as ILayout)}>{renderItem(item)}</div>
				</li>
			);
		});
	}, [currentStreams, t('no-calls'), layout]);

	const renderAudioView = useMemo(() => {
		return audioStreams().map((item, index) => {
			return (
				// 设置唯一key，避免排序时，导致组件重新渲染
				<li className={calculatorLiClassNames(layout as ILayout)} key={`${item.id}` || index}>
					<div className={calculatorVideoClassNames(layout as ILayout)}>{renderItem(item)}</div>
				</li>
			);
		});
	}, [audioStreams(), layout]);

	// console.log(currentStreams, audioStreams(), 'audioStreams');

	return (
		<div className="other-stream-container" style={{ width: width, height: height }} id={'other-stream-container'}>
			<ul className={layout === 'full' ? 'up-down-ul' : 'left-ul'}>{renderView}</ul>
			<ul style={{ display: 'none' }}>{renderAudioView}</ul>
			<SyncScreen></SyncScreen>
		</div>
	);
};

export default OtherStream;
